#include "stdafx.h"
#include "SpinBoxDelegate.h"
#include <QSpinBox>
#include <QVector>
#include <QMouseEvent>
#include <QDoubleSpinBox>

SpinBoxDelegate::SpinBoxDelegate(QObject *parent)
	: QItemDelegate(parent)
{
	m_bEnable = true;
}

SpinBoxDelegate::~SpinBoxDelegate()
{

}

void SpinBoxDelegate::setEnable( bool bEnable)
{
	m_bEnable = bEnable;
}

void SpinBoxDelegate::setColumnsForDoubleBox( QVector<int>& vetColumns )
{
	m_vetDoubleBox = vetColumns;
}

QWidget * SpinBoxDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
	int nColumn = index.column();

	if(m_vetDoubleBox.contains(nColumn))
	{
		QDoubleSpinBox*editor = new QDoubleSpinBox(parent);
		editor->setMinimum(0);
		editor->setMaximum(999999.9999);
		return editor;
	}
	else
	{
		QSpinBox *editor = new QSpinBox(parent);
		editor->setMinimum(0);
		editor->setMaximum(999999);
		return editor;
	}
	
}

void SpinBoxDelegate::setEditorData( QWidget *editor, const QModelIndex &index ) const
{
	int nColumn = index.column();

	if(m_vetDoubleBox.contains(nColumn))
	{
		float value = index.model()->data(index,Qt::EditRole).toFloat();
		QDoubleSpinBox *spinbox = static_cast<QDoubleSpinBox*>(editor);
		spinbox->setValue(value);
	}
	else
	{
		int value = index.model()->data(index,Qt::EditRole).toInt();
		QSpinBox *spinbox = static_cast<QSpinBox*>(editor);
		spinbox->setValue(value);
	}
	
}

void SpinBoxDelegate::setModelData( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const
{
	int nColumn = index.column();

	if(m_vetDoubleBox.contains(nColumn))
	{
		QDoubleSpinBox *spinbox = static_cast<QDoubleSpinBox*>(editor);
		spinbox->interpretText();
		float value = spinbox->value();
		model->setData(index,value,Qt::EditRole);
	}

	else
	{
		QSpinBox *spinbox = static_cast<QSpinBox*>(editor);
		spinbox->interpretText();
		int value = spinbox->value();
		model->setData(index,value,Qt::EditRole);
	}
	
}

void SpinBoxDelegate::updateEditorGeometry( QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
	editor->setGeometry(option.rect);
}

bool SpinBoxDelegate::editorEvent( QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index )
{
	QRect decorationRect = option.rect;
	QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
	if (event->type() == QEvent::MouseButtonPress && decorationRect.contains(mouseEvent->pos()) && m_bEnable)
	{
		//if (index.column() == m_nColumnIndex)
		//{
		//	bool data = model->data(index, Qt::CheckStateRole).toBool();
		//	model->setData(index, !data, Qt::UserRole);
		//}
	}
	return QItemDelegate::editorEvent(event,model,option,index);
}
